<template>
  <view class="info-body">
    <view class="top-container">
      <view class="top-card">
        <view class="top-no">
          <span>维修单号</span>
          <span>{{ params.repair_code }}</span>
        </view>
        <span class="repair-title">{{ params.repair_name }}</span>
        <up-line length="calc(100% - 40rpx)" margin="20rpx 20rpx"></up-line>
        <view>
          <view class="title-item"><span>维修人 {{ params.repair_personnel_name }}</span></view>
          <view class="title-item"><span>故障说明 {{ params.fault_description }}</span></view>
          <view class="title-item"><span>报修时间 {{ params.repair_date }}</span></view>
          <view class="title-item"><span>期望修复日期 {{ params.expect_repair_date }}</span></view>
        </view>
      </view>
      <view class="attachment">
        <span>附件</span>
      </view>
    </view>
    <view class="content-container">
      <view class="content-top">
        <span>资产列表</span>
        <span>共计:{{ total }}</span>
      </view>
      <scroll-view scroll-y="true">
        <view class="content-data" v-for="(item,index) in dataList" :key="index">
          <view class="content-info">
            <image :src="`${BASE_URL}/File/GetImage?fileId=${item.image}`"></image>
            <view class="content-info-right">
              <span>{{ item.asset_name }}</span>
              <span>使用部门 {{ item.department_name }}</span>
              <span>使用人 {{ item.user_name }}</span>
              <span>存放地点 {{ item.local_name }}</span>
              <span>资产编码 {{ item.asset_code }}</span>
              <span>标签编码 {{ item.label_number }}</span>
            </view>
          </view>
          <view class="content-form">
            <up-form labelPosition='top' label-width="150rpx" v-model="dataParams[index]">
              <up-form-item label="维修金额" required>
                <up-input v-model="dataParams[index].money" placeholder="请输入维修金额"></up-input>
              </up-form-item>
              <up-form-item label="维修说明" required>
                <up-textarea v-model="dataParams[index].repair_desc" placeholder="请填写维修说明"></up-textarea>
              </up-form-item>
              <up-form-item label="附件">
                <view class="form-section" style="padding: 20rpx">
                  <!-- 上传规则提示文本 -->
                  <view
                      v-if="!pageDisabled"
                      style="margin-bottom: 10rpx; font-size: 24rpx; color: #888"
                  >
                    支持上传格式：
                    <text style="color: red"
                    >png, jpg, jpeg, pdf, txt, doc, docx, xls, xlsx
                    </text
                    >
                    ， 最大文件：
                    <text style="color: red">{{ maxSize / 1024 / 1024 }}MB</text>
                    ，
                    最多上传：
                    <text style="color: red">{{ maxCount }} 个文件</text>
                  </view>

                  <up-button type="primary" v-if="!pageDisabled" @click="selectFile(item,index)"
                  >点击上传文件
                  </up-button
                  >
                  <!-- 已选文件展示 -->
                  <view
                      v-if="attachmentsUploadList[index][0].files.length"
                      style="margin-top: 10rpx"
                  >
                    已上传文件：
                    <view
                        style="display: flex"
                        v-for="items in attachmentsUploadList[index][0].files"
                        :key="items.id"
                    >
                      <text style="color: red" @click="handleDownFile(items)">{{
                          items.name
                        }}
                      </text>
                      <up-icon
                          v-if="!pageDisabled"
                          @click="handleClose(items,index)"
                          name="close"
                          color="#ccc"
                      />
                    </view>
                  </view>
                </view>
              </up-form-item>
            </up-form>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="footer-bar" @click="saveData">
      <span>确定</span>
    </view>
  </view>
</template>

<script setup>
import {ref, reactive} from 'vue';
import {onLoad} from "@dcloudio/uni-app";
import http, {BASE_URL} from "@/api/request";
import fileSys from "@/utils/fileSys";
import {formatDateTime} from "@/utils";

const maxSize = 10 * 1024 * 1024; // 10MB
const maxCount = 10;
const allowedExts = [
  "png",
  "jpg",
  "jpeg",
  "pdf",
  "txt",
  "doc",
  "docx",
  "xls",
  "xlsx",
];

const params = ref({});
const dataList = ref([])
const total = ref(0)
const dataParams = ref([])

const pageId = ref("");
const pageDisabled = ref(false);
const attachmentsUploadList = reactive([]);

const attachmentsUpload = ref([
  {
    Fileld: [],
    files: [],
    linkId: "1",
    taskId: "<%assetrepairmstr.id%>",
  },
]);

onLoad((options) => {
  params.value = JSON.parse(options.item)
  attachmentsUpload.value[0].taskId = params.value.id
  const data = {
    code: "getAssetListByRepairCode",
    allColumnFilter: true,
    filters: [
      {
        name: 'repair_code',
        value: params.value.repair_code
      }
    ],
    pageInput: {currentPage: 1, pageSize: 999},
    permissionKey: ""
  };
  http.post("/api/module/GetViewTable", data).then((res) => {
    if (res.code && res.isSuccess) {
      dataList.value = res.result.viewTable
      total.value = res.result.viewTable.length
      for (let i = 0; i < total.value; i++) {
        dataParams.value.push({
          id: res.result.viewTable[i].id,
          fileId: '',
          money: '',
          repair_desc: ''
        })
        attachmentsUploadList.push([
          {
            Fileld: [],
            files: [],
            linkId: "1",
            taskId: params.value.id,
            parentId: res.result.viewTable[i].id
          }
        ])
      }
    }
  });
  getPageInfo()
})

const getPageInfo = async () => {
  const data = {
    assetlist: "assetrepair",
    pageCode: "repair",
  };

  const {code, isSuccess, result} = await http.post(
      "/api/page/GetPageInfoByCode",
      data
  );
  if (code && isSuccess) {
    pageId.value = result.page.parentPageId;
  }
};

const handleClose = (items,index) => {
  attachmentsUploadList[index][0].files = attachmentsUploadList[index][0].files.filter(
      (item) => item.id !== items.id
  );
};

const selectFile = (item,index) => {
  if (attachmentsUploadList[index][0].files.length === 10) {
    uni.showLoading({
      title: "超出限制！",
      type: "error",
    });
  } else {
    fileSys().then((res) => {
      const userInfo = JSON.parse(uni.getStorageSync("userInfo"));
      attachmentsUploadList[index][0].files.push({
        id: res[0].id,
        name:
            (res[0].fileName || "未知文件") +
            "  " +
            userInfo.name +
            "  " +
            formatDateTime(new Date()),
        url: `/File/Download?fileId=` + res[0].id
      });
    });
  }
};

const handleDownFile = (items) => {
  uni.downloadFile({
    url: BASE_URL + items.url,
    success: (res) => {
      if (res.statusCode === 200) {
        plus.runtime.openFile(res.tempFilePath, {}, (e) => {
          uni.showModal({
            title: "无法打开文件",
            content: "请安装 WPS Office 或 QQ 浏览器等可打开该文件的应用",
            confirmText: "去安装",
            success: (modalRes) => {
              if (modalRes.confirm) {
                try {
                	plus.runtime.openURL('market://details?id=com.tencent.mtt', () => {
                		plus.runtime.openURL('https://browser.qq.com');
                	});
                } catch (e) {
                	plus.runtime.openURL('https://browser.qq.com');
                }
              }
            },
          });
        });
      }
    },
    fail: (err) => {
      console.error("下载失败", err);
      uni.showToast({title: "下载失败", icon: "none"});
    },
  });
};

const saveData = () => {
  for (let val of dataParams.value) {
    if (!val.money || !val.repair_desc) {
      uni.showToast({
        title: '参数不正确',
        icon: 'none',
      })
      return
    }
  }
  for (let i = 0; i < dataParams.value.length; i++) {
    for (let j = 0; j < attachmentsUploadList.length; j++) {
      if (dataParams.value[i].id === attachmentsUploadList[j][0].parentId) {
        dataParams.value[i].files = attachmentsUploadList[i][0].files.map(item => item.id).join(',')
        dataParams.value[i].repair_status = 'COMPLETED'
      }
    }
  }

  let p = {
    pageId: '2d572fdd-651e-41ae-bbe2-ff9f93dd33e5',
    methodName: 'doSaveTableData',
    saveTableDataRequest: {
      data: {
        insert: {},
        update: {
          assetrepairmstr: {
            id: params.value.id,
            repair_state: 'ALL_REPAIR'
          },
          assetrepairdet: dataParams.value
        },
        remove: {},
        otherData: {
          fileAttachments: attachmentsUpload.value
        }
      }
    }
  }
  http.post('/api/module/Invoke', p).then(res => {
    if (res.isSuccess) {
      uni.showToast({
        title: '操作成功',
        icon: 'none',
        complete: () => {
          uni.navigateBack(-1)
        }
      })
    }
  }).catch(err => {
    console.error(err)
  })
}

</script>

<style lang="scss" scoped>
.info-body {
  height: calc(100vh - var(--window-top, 0px));
}

.top-container {

  height: 620rpx;
  background: #4792FD;
  display: flex;
  flex-direction: column;
  align-items: center;

  .top-card {
    margin-top: 20rpx;
    height: 420rpx;
    width: 90%;
    background-color: #4D96FF;
    border-radius: 10rpx;

    .top-no {
      margin: 20rpx;
      height: 45rpx;
      display: flex;
      align-items: center;

      & > span:first-child {
        background-color: white;
        padding: 10rpx;
        border-radius: 8rpx;
        color: #4792FD;
      }

      & > span:last-child {
        margin-left: 30rpx;
        color: white;
      }
    }

    .repair-title {
      margin: 20rpx;
      color: #D8ECF1;
    }

    view {
      margin: 0 20rpx;

      .title-item {
        margin: 20rpx 0;
        color: #D8ECF1;
      }
    }
  }

  .attachment {
    margin-top: 20rpx;
    width: 100%;
    height: 140rpx;
    width: 90%;
    background-color: #4D96FF;
    border-radius: 10rpx;

    & > span {
      display: block;
      color: #D8ECF1;
      margin: 20rpx;
    }
  }
}

.content-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 750rpx);
  overflow-y: auto;

  .content-top {
    display: flex;
    align-items: center;
    padding: 0 20rpx;
    color: #4D84D2;
    height: 100rpx;
    justify-content: center;
    width: 100%;
    background-color: white;

    & > span:last-child {
      margin-left: auto;
    }
  }

  .content-data {
    width: calc(100% - 40rpx);
    margin: 20rpx 20rpx 60rpx 20rpx;
    background-color: white;
    border-radius: 10rpx;
    padding: 10rpx;

    .content-info {
      display: flex;
      padding: 10rpx;
      width: 100%;
      border-bottom: 1px solid #ccc;

      image {
        height: 250rpx;
        width: 250rpx;
      }

      .content-info-right {
        margin-left: 20rpx;
        display: flex;
        flex-direction: column;
        width: calc(100% - 260rpx);

        & > span:nth-child(1) {
          font-size: 1.3rem
        }

        & > :nth-child(n+2) {
          color: #CBCACE;
        }


      }
    }

    .content-form {
      width: calc(100% - 40rpx);
      margin: 20rpx;
    }
  }
}

.footer-bar {
  height: 150rpx;
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  flex: 1;
  background-color: #509EFF;
  display: flex;
  align-items: center;
  justify-content: center;

  span {
    color: white;
  }
}
</style>